﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Media.Imaging;
using EbbinghausWord.BLL;
using EbbinghausWord.Entities;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace EbbinghausWord.Pages
{
    public partial class ReviewWordPage : PhoneApplicationPage
    {
        public ReviewWordPage()
        {
            InitializeComponent();
        }

        #region private field
        private WordEntity _currentWord = null;
        private bool _isMouseMove = false;
        #endregion

        #region callback
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            ShowFirstWord();
        }

        private void ShowChinese_Click(object sender, RoutedEventArgs e)
        {
            ShowChinesePanel();
        }

        private void RemeberWord_Click(object sender, RoutedEventArgs e)
        {
            if (_currentWord != null)
            {
                _currentWord = WordBookManager.RememberWord();
            }

            ShowWord();
        }

        private void ForgetWordButton_Click(object sender, RoutedEventArgs e)
        {
            _currentWord = WordBookManager.RorgetWord();

            ShowWord();
        }

        private void PhoneApplicationPage_Unloaded(object sender, RoutedEventArgs e)
        {
            StoreManager.SaveUserWordbook();
        }

        private void AboutClick(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(@"/Pages/About.xaml", UriKind.Relative));
        }

        private void OptionClick(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(@"/Pages/Option.xaml", UriKind.Relative));
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (WordBookManager.IsNeedReflesh)
            {
                //清空队列
                WordQueueManager.InitQueue();
                //显示第一个单词
                ShowFirstWord();
                WordBookManager.IsNeedReflesh = false;
            }

            ShowAllControls();

            base.OnNavigatedTo(e);
        }

        private void chinesePanel_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (!_isMouseMove)
            {
                HideChinesePanel();
            }
        }

        private void chinesePanel_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            _isMouseMove = false;
        }

        private void chinesePanel_ManipulationDelta(object sender, System.Windows.Input.ManipulationDeltaEventArgs e)
        {
            _isMouseMove = true;
        }

        private void CompleteRemeberButton_Click(object sender, EventArgs e)
        {
            if (_currentWord == null)
            {
                Tools.ShowMessage("目前没有要学习的单词");
                return;
            }

            if (MessageBox.Show("是否排除单词，确定后，该单词将不再出现在你的复习和学习计划中", "排除单词",
                MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                _currentWord = WordBookManager.CompleteRemeberWord();
                ShowWord();
            }
        }

        private void studyAchievementBarIconButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/StudyAchievementPage.xaml", UriKind.Relative));
        }

        private void scoreBarIconButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/ScorePage.xaml", UriKind.Relative));
        }

        private void MainME_MediaOpened(object sender, RoutedEventArgs e)
        {
            MainME.Play();
        }

        private void MainME_MediaFailed(object sender, ExceptionRoutedEventArgs e)
        {
            //删除文件
            VoiceManager.DeleteVoiceFile(_currentWord.English);
            ShowVoiceImage();
            //重新下载
            Tools.ShowMessage("播放失败，发音文件被删除");
            MainME.Source = null;
        }

        private void voiceImage_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            PlayVoice();
        }

        /// <summary>
        /// 播放声音
        /// </summary>
        private void PlayVoice()
        {
            var voiceManager = new VoiceManager();
            voiceManager.GetVoiceCompleted += (s, ex) =>
                                                  {
                                                      MainME.SetSource(ex.VoiceFileStream);
                                                      MainME.Position = new TimeSpan(0);
                                                      ShowVoiceImage();
                                                  };

            voiceManager.GetVoiceFailed += (s, ex) =>
                                               {
                                                   Tools.ShowMessage("发音文件获取失败，请检查网络连接");
                                                   ShowVoiceImage();
                                               };

            voiceManager.GetVoiceAsync(_currentWord.English);
        }

        private void MainME_MediaEnded(object sender, RoutedEventArgs e)
        {
            MainME.Source = null;
        }


        #endregion

        #region private method

        /// <summary>
        /// 隐藏中文及音标面板
        /// </summary>
        private void HideChinesePanel()
        {
            chinesePanel.Visibility = Visibility.Collapsed;
            ShowChineseButton.Visibility = Visibility.Visible;
            ForgetWordButton.IsEnabled = false;
            RemeberWordButton.IsEnabled = false;
        }

        /// <summary>
        /// 显示中文及音标面板
        /// </summary>
        private void ShowChinesePanel()
        {
            chinesePanel.Visibility = Visibility.Visible;
            ShowChineseButton.Visibility = Visibility.Collapsed;
            ForgetWordButton.IsEnabled = true;
            RemeberWordButton.IsEnabled = true;
        }

        /// <summary>
        /// 显示当前单词
        /// </summary>
        private void ShowWord()
        {
            if (_currentWord == null)
            {
                Tools.ShowMessage("目前没有需要记忆的单词");
                HideAllControls();
                return;
            }

            DataContext = _currentWord;
            HideChinesePanel();
            ShowWordInfo();

            //设置词组、同义词的绑定关系
            SetItemsSource();

            //显示单词的发音文件
            ShowVoiceImage();

            //如果存在发音文件，并且允许自动播放，则直接播放声音
            if (VoiceManager.IsFileExist(_currentWord.English) && new UserConfig().IsAutoPlayVoice)
            {
                PlayVoice();
            }
        }

        /// <summary>
        /// 设置词组、同义词的绑定关系
        /// </summary>
        private void SetItemsSource()
        {
            var wordGroups = DictionaryManager.GetWordDictionary()[_currentWord.English].WordGroups;
            if (new UserConfig().IsShowWordGroup && (wordGroups != null) && (wordGroups.Count != 0))
            {
                wordGroupListBox.ItemsSource = wordGroups;
                wordGroupStackPanel.Visibility = Visibility.Visible;
            }
            else
            {
                wordGroupStackPanel.Visibility = Visibility.Collapsed;
            }

            var sentences = DictionaryManager.GetWordDictionary()[_currentWord.English].Sentences;
            if (new UserConfig().IsShowSentence && (sentences != null) && (sentences.Count != 0))
            {
                sentenceListBox.ItemsSource = sentences;
                sentenceStackPanel.Visibility = Visibility.Visible;
            }
            else
            {
                sentenceStackPanel.Visibility = Visibility.Collapsed;
            }

            var synonyms = DictionaryManager.GetWordDictionary()[_currentWord.English].Synonyms;
            if (new UserConfig().IsShowSynonym && (synonyms != null) && (synonyms.Count != 0))
            {
                synonmyListBox.ItemsSource = synonyms;
                synonmyLStackPanel.Visibility = Visibility.Visible;
            }
            else
            {
                synonmyLStackPanel.Visibility = Visibility.Collapsed;
            }
        }

        /// <summary>
        /// 显示单词的发音文件
        /// </summary>
        private void ShowVoiceImage()
        {
            if (VoiceManager.IsFileExist(_currentWord.English))
            {
                ((BitmapImage)voiceImage.Source).UriSource = new Uri("/Images/voice.png", UriKind.Relative);
            }
            else
            {
                ((BitmapImage)voiceImage.Source).UriSource = new Uri("/Images/voice-nofile.png", UriKind.Relative);
            }
        }

        /// <summary>
        /// 显示当前单词进度
        /// </summary>
        private void ShowWordInfo()
        {
            totalTextBlock.Text = string.Format(@"记住{0} 共{1} 队列{2}  ",
                          WordBookManager.WordBook.Count(x => x.IsInTheWordBook),
                          WordBookManager.WordBook.Count, WordQueueManager.Count);

            wordbookTextBlock.Text = _currentWord.IsInTheWordBook ? "复习" : "学习";
            remeberLevelTextBlock.Text = _currentWord.IsInTheWordBook ? "记忆级别" + _currentWord.RememberLevel
                : "记忆次数" + _currentWord.RememberTimes;
        }

        /// <summary>
        /// 显示第一个单词
        /// </summary>
        private void ShowFirstWord()
        {
            //获取下一个单词
            _currentWord = WordBookManager.GetNextWord();

            ShowWord();
        }

        /// <summary>
        /// 隐藏所有控件
        /// </summary>
        private void HideAllControls()
        {
            ContentPanel.Visibility = Visibility.Collapsed;
            buttonPanel.Visibility = Visibility.Collapsed;
        }

        /// <summary>
        /// 显示所有控件
        /// </summary>
        private void ShowAllControls()
        {
            ContentPanel.Visibility = Visibility.Visible;
            buttonPanel.Visibility = Visibility.Visible;
        }

        #endregion

        private ProgressIndicator _progressIndicator;

        private void testButton_Click(object sender, EventArgs e)
        {
            if (null == _progressIndicator)
            {
                _progressIndicator = new ProgressIndicator();
                _progressIndicator.IsVisible = true;
                SystemTray.ProgressIndicator = _progressIndicator;
            }

            _progressIndicator.IsIndeterminate = true;
        }

        private void ad_Click(object sender, EventArgs e)
        {
            hintControl.Visibility = Visibility.Visible;
        }
    }
}